package com.kyz.speechsdk.engine.helper;

/**
 * create by ZhongZihao on 2020/12/29
 */
class StringMatcher {
    //通配符
    private static final char WILDCARD = '%';

    public static boolean isMatch(String sentence, String keyword) {
        int sRight = sentence.length(), pRight = keyword.length();
        while (sRight > 0 && pRight > 0 && keyword.charAt(pRight - 1) != WILDCARD) {
            if (charMatch(sentence.charAt(sRight - 1), keyword.charAt(pRight - 1))) {
                --sRight;
                --pRight;
            } else {
                return false;
            }
        }

        if (pRight == 0) {
            return sRight == 0;
        }

        int sIndex = 0, pIndex = 0;
        int sRecord = -1, pRecord = -1;

        while (sIndex < sRight && pIndex < pRight) {
            if (keyword.charAt(pIndex) == WILDCARD) {
                ++pIndex;
                sRecord = sIndex;
                pRecord = pIndex;
            } else if (charMatch(sentence.charAt(sIndex), keyword.charAt(pIndex))) {
                ++sIndex;
                ++pIndex;
            } else if (sRecord != -1 && sRecord + 1 < sRight) {
                ++sRecord;
                sIndex = sRecord;
                pIndex = pRecord;
            } else {
                return false;
            }
        }

        return allWildcard(keyword, pIndex, pRight);
    }

    private static boolean allWildcard(String str, int left, int right) {
        for (int i = left; i < right; ++i) {
            if (str.charAt(i) != WILDCARD) {
                return false;
            }
        }
        return true;
    }

    private static boolean charMatch(char u, char v) {
        return u == v;
    }

}
